<!DOCTYPE html>
<!--
  The MIT License (MIT)

  Copyright (c) 2017 Tarek Sherif

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<!-- 
    Outlining algorithm from: https://learnopengl.com/#!Advanced-OpenGL/Stencil-testing
 -->
<html>
<head>
    <title>PicoGL.js: Outline</title>
    <meta charset="utf-8">
    <script src="utils/gl-matrix.js"></script>
    <script src="../build/picogl.js"></script>
    <script src="utils/utils.js"></script>
    <link rel="stylesheet" href="../site/css/picogl-example.css"> 
    <style>
        #ssao-controls {
            position: absolute;
            bottom: 20px;
            right: 20px;
            color: white;
        }
    </style>
</head>
<body>
    <div id="example-title">
        PicoGL.js Example: Outline
        <div>
            <a href="https://github.com/tsherif/picogl.js/blob/master/examples/outline.html">Source code</a>
        </div>
    </div>
    <canvas id="gl-canvas"></canvas>
    <script type="x-shader/vs" id="vertex-main">
        #version 300 es

        layout(std140, column_major) uniform;
        
        layout(location=0) in vec4 position;
        layout(location=1) in vec2 uv;
        layout(location=2) in vec3 normal;
        layout(location=3) in mat4 modelMatrix;
        
        uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
            vec4 uLightPosition;
        };       
        
        out vec4 vPosition;
        out vec2 vUV;
        out vec4 vNormal;

        void main() {
            vPosition = modelMatrix * position;
            vNormal = modelMatrix * vec4(normal, 0.0);
            vUV = uv;
            gl_Position = uViewProj * vPosition;
          }
    </script>
    <script type="x-shader/fs" id="fragment-main">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;

        uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
            vec4 uLightPosition;
        };

        uniform sampler2D uTexture;
        
        in vec4 vPosition;
        in vec2 vUV;
        in vec4 vNormal;

        out vec4 fragColor;
        void main() {
            vec3 position = vPosition.xyz;
            vec3 normal = normalize(vNormal.xyz);
            vec2 uv = vUV;

            vec4 baseColor = texture(uTexture, uv);
            vec3 eyeDirection = normalize(uEyePosition.xyz - position);
            vec3 lightVec = uLightPosition.xyz - position;
            vec3 lightDirection = normalize(lightVec);
            vec3 reflectionDirection = reflect(-lightDirection, normal);
            float nDotL = max(dot(lightDirection, normal), 0.0);
            float diffuse = nDotL;
            float ambient = 0.2;
            float specular = pow(max(dot(reflectionDirection, eyeDirection), 0.0), 20.0);

            fragColor = vec4((ambient + diffuse + specular) * baseColor.rgb, 1.0);
        }
    </script>
    <script type="x-shader/vs" id="vertex-outline">
        #version 300 es

        layout(std140, column_major) uniform;
        
        layout(location=0) in vec4 position;
        layout(location=3) in mat4 modelMatrix;
        
        uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
            vec4 uLightPosition;
        };       
        
        void main() {
            gl_Position = uViewProj * modelMatrix * (vec4(1.1, 1.1, 1.1, 1.0) * position);
          }
    </script>
    <script type="x-shader/fs" id="fragment-outline">
        #version 300 es
        precision highp float;

        out vec4 fragColor;
        void main() {
            fragColor = vec4(1.0, 1.0, 0.0, 1.0);
        }
    </script>
    <script type="text/javascript">
        utils.addTimerElement();

        var NUM_SPHERES = 32;
        var NUM_PER_ROW = 8;
        var SPHERE_RADIUS = 0.6;
        var NEAR = 0.1;
        var FAR = 10.0;


        if (!utils.testWebGL2()) {
            console.error("WebGL 2 not available");
            document.body.innerHTML = "This example requires WebGL 2 which is unavailable on this system."
        }

        var canvas = document.getElementById("gl-canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var spheres = new Array(NUM_SPHERES);
        var modelMatrixData = new Float32Array(NUM_SPHERES * 16);

        for (var i = 0; i < NUM_SPHERES; ++i) {
            var angle = 2 * Math.PI * (i % NUM_PER_ROW) / NUM_PER_ROW;
            var x = Math.sin(angle) * SPHERE_RADIUS;
            var y = Math.floor(i / NUM_PER_ROW) / (NUM_PER_ROW / 4) - 0.75;
            var z = Math.cos(angle) * SPHERE_RADIUS;
            spheres[i] = {
                scale: [0.8, 0.8, 0.8],
                rotate: [0, 0, 0], // Will be used for global rotation
                translate: [x, y, z],
                modelMatrix: mat4.create()
            };
        }

        // CREATE APP WITH STENCIL BUFFER
        var app = PicoGL.createApp(canvas, { stencil: true })
        .clearColor(0.0, 0.0, 0.0, 1.0)
        .clearMask(PicoGL.COLOR_BUFFER_BIT | PicoGL.DEPTH_BUFFER_BIT | PicoGL.STENCIL_BUFFER_BIT)
        .depthFunc(PicoGL.LEQUAL)
        // ENABLE STENCIL TESTING
        .stencilTest()
        // SET STENCIL TEST TO UPDATE STENCIL VALUE WHEN 
        // DEPTH AND STENCIL TESTS PASS
        .stencilOp(PicoGL.KEEP, PicoGL.KEEP, PicoGL.REPLACE);

        var timer = app.createTimer();

        // SET UP MAIN DRAW PROGRAM
        var mainVsSource =  document.getElementById("vertex-main").text.trim();
        var mainFsSource =  document.getElementById("fragment-main").text.trim();
        var mainProgram = app.createProgram(mainVsSource, mainFsSource);

        // SET UP OUTLINE PROGRAM, WHICH SCALES UP GEOMETRY AND DRAWS
        // IN SOLID YELLOW 
        var outlineVsSource =  document.getElementById("vertex-outline").text.trim();
        var outlineFsSource =  document.getElementById("fragment-outline").text.trim();
        var outlineProgram = app.createProgram(outlineVsSource, outlineFsSource);


        // INSTANCED SPHERE GEOMETRY
        var sphere = utils.createSphere({radius: 0.5});
        var positions = app.createVertexBuffer(PicoGL.FLOAT, 3, sphere.positions);
        var uv = app.createVertexBuffer(PicoGL.FLOAT, 2, sphere.uvs);
        var normals = app.createVertexBuffer(PicoGL.FLOAT, 3, sphere.normals);
        var indices = app.createIndexBuffer(PicoGL.UNSIGNED_SHORT, 3, sphere.indices);

        // PER-INSTANCE MODEL MATRICES
        var modelMatrices = app.createMatrixBuffer(PicoGL.FLOAT_MAT4, modelMatrixData);

        var sphereArray = app.createVertexArray()
        .vertexAttributeBuffer(0, positions)
        .vertexAttributeBuffer(1, uv)
        .vertexAttributeBuffer(2, normals)
        .instanceAttributeBuffer(3, modelMatrices)
        .indexBuffer(indices);

        // UNIFORM DATA
        var projMatrix = mat4.create();
        mat4.perspective(projMatrix, Math.PI / 2, canvas.width / canvas.height, NEAR, FAR);

        var viewMatrix = mat4.create();
        var eyePosition = vec3.fromValues(0, 0.8, 2);
        mat4.lookAt(viewMatrix, eyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));

        var viewProjMatrix = mat4.create();
        mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);

        var lightPosition = vec3.fromValues(0.5, 1, 2); 

        // UNIFORM BUFFERS
        var sceneUniforms = app.createUniformBuffer([
            PicoGL.FLOAT_MAT4,
            PicoGL.FLOAT_VEC4,
            PicoGL.FLOAT_VEC4
        ])
        .set(0, viewProjMatrix)
        .set(1, eyePosition)
        .set(2, lightPosition)
        .update();

        window.onresize = function() {
            app.resize(window.innerWidth, window.innerHeight);

            mat4.perspective(projMatrix, Math.PI / 2, app.width / app.height, 0.1, 10.0);
            mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);
            sceneUniforms.set(0, viewProjMatrix).update();
        };

        
        utils.loadImages(["img/webgl-logo.png"], function(images) {
            // CREATE TEXTURE
            var texture = app.createTexture2D(images[0], { flipY: true });

            // DRAW CALLS
            var mainDrawcall = app.createDrawCall(mainProgram, sphereArray)
            .uniformBlock("SceneUniforms", sceneUniforms)
            .texture("uTexture", texture);

            var outlineDrawcall = app.createDrawCall(outlineProgram, sphereArray)
            .uniformBlock("SceneUniforms", sceneUniforms);

            var rotationMatrix = mat4.create();

            function draw() {
                if (timer.ready()) {
                    utils.updateTimerElement(timer.cpuTime, timer.gpuTime);
                }

                timer.start();

                // UPDATE TRANSFORMS
                for (var i = 0, len = spheres.length; i < len; ++i) {
                    spheres[i].rotate[1] += 0.002;

                    utils.xformMatrix(spheres[i].modelMatrix, spheres[i].translate, null, spheres[i].scale);
                    mat4.fromYRotation(rotationMatrix, spheres[i].rotate[1]);
                    mat4.multiply(spheres[i].modelMatrix, rotationMatrix, spheres[i].modelMatrix)

                    modelMatrixData.set(spheres[i].modelMatrix, i * 16);
                }

                modelMatrices.data(modelMatrixData);

                app.clear()
                .depthTest()
                // SET STENCIL VALUE TO 1 FOR EVERY PIXEL
                // THAT GETS DRAWN
                .stencilFunc(PicoGL.ALWAYS, 1, 0xFF)
                .stencilMask(0xFFFF);
                mainDrawcall.draw();
                
                app.noDepthTest()
                // ONLY DRAW WHERE STENCIL VALUE IS NOT 1
                // (I.E. WHERE WE DIDN'T DRAW BEFORE)
                .stencilFunc(PicoGL.NOTEQUAL, 1, 0xFF)
                .stencilMask(0);
                outlineDrawcall.draw();
                
                timer.end();

                requestAnimationFrame(draw);
            }

            requestAnimationFrame(draw);
            
        });

    </script>
    <a href="https://github.com/tsherif/picogl.js" id="github-ribbon"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
    <script src="../site/js/iframe.js"></script>
</body>
</html>
